package com.lzx.controller;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.PageInfo;
import com.lzx.api.CommonResult;
import com.lzx.dao.repository.ProductRepository;
import com.lzx.dto.ProductDto;
import com.lzx.entity.Product;
import com.lzx.service.BrandService;
import com.lzx.service.CategoryService;
import com.lzx.service.PictrueService;
import com.lzx.service.ProductService;
import com.lzx.util.PageUtil;
import io.netty.util.internal.StringUtil;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * (Product)表控制层
 *
 * @author makejava
 * @since 2021-02-24 17:27:04
 */
@RestController
@RequestMapping("product")
public class ProductController {
    /**
     * 服务对象
     */
    @Autowired
    private ProductService productService;
    @Autowired
    private BrandService brandService;
    @Autowired
    private ElasticsearchRestTemplate restTemplate;
    @Autowired
    private ProductRepository productRepository;

    /**
     * 通过主键查询单条数据
     *
     * @param productId 主键
     * @return 单条数据
     */
    @GetMapping("/getDetails")
    public CommonResult getDetail(@RequestParam Integer productId) {
        Product product = this.productService.getById(productId);
        if (BeanUtil.isNotEmpty(product)) {
            return CommonResult.success(product);
        }
        return CommonResult.failed();
    }

    /**
     * 根据条件获取商品列表
     *
     * @param request
     * @return
     */
    @RequestMapping("/list")
    public CommonResult productlist(HttpServletRequest request) {
        /*同步ES数据*/
        productService.dbToEs();

        String id = request.getParameter("id");
        String categoryId = request.getParameter("categoryId");
        String brandId = request.getParameter("brandId");
        String keyWord = request.getParameter("search");
        String pagenum = request.getParameter("page");
        String pagesize = request.getParameter("rows");
        String isactive = request.getParameter("saleable");

        boolean isNullQuery = BeanUtil.isEmpty(categoryId) && BeanUtil.isEmpty(brandId)&&BeanUtil.isEmpty(keyWord)&&BeanUtil.isEmpty(categoryId);

        Set<ProductDto> resultSet = new HashSet<>();
        /*传入了商品id，实施精确搜索*/
        if (id != null) {
            ProductDto dto = productRepository.queryById(Integer.valueOf(id));
            resultSet.add(dto);
        } else {
            /*没有传入任何条件，获取所有商品*/
            if (isNullQuery) {
                productRepository.findAll().forEach(resultSet::add);
            }
            /*根据关键字搜索*/
            if (keyWord != null) {
                resultSet.addAll(productRepository.queryByNameOrderByIdDesc(keyWord));
                resultSet.addAll(productRepository.queryByBrandOrderByIdDesc(keyWord));
                resultSet.addAll(productRepository.queryByCaptionOrderByIdDesc(keyWord));

            }
            /*同时根据分类和品牌搜索*/
            if(BeanUtil.isNotEmpty(categoryId)&&brandId!=null){
                String brand = brandService.queryById(Integer.valueOf(brandId)).getName();
                NativeSearchQuery query = new NativeSearchQueryBuilder().withQuery(QueryBuilders.boolQuery().must(QueryBuilders.matchQuery("categories.id",Integer.valueOf(categoryId))).must(QueryBuilders.matchQuery("brand",brand))).build();
                List<SearchHit<ProductDto>> searchHits = restTemplate.search(query, ProductDto.class).getSearchHits();
                for (SearchHit<ProductDto> searchHit : searchHits) {
                    resultSet.add(searchHit.getContent());
                }
            }else {
                /*只根据分类搜索*/
                if (BeanUtil.isNotEmpty(categoryId)) {

                    NativeSearchQuery query = new NativeSearchQueryBuilder().withQuery(QueryBuilders.matchQuery("categories.id", Integer.valueOf(categoryId))).withSort(SortBuilders.fieldSort("id")).build();
                    List<SearchHit<ProductDto>> searchHits = restTemplate.search(query, ProductDto.class).getSearchHits();
                    for (SearchHit<ProductDto> searchHit : searchHits) {
                        resultSet.add(searchHit.getContent());
                    }
                }
                /*只根据品牌搜索*/
                if (brandId != null) {
                    String brand = brandService.queryById(Integer.valueOf(brandId)).getName();
                    resultSet.addAll(productRepository.queryByBrandOrderByIdDesc(brand));
                }
            }
        }
        /*根据商品状态筛选*/
        if (isactive != null) {
           resultSet = resultSet.stream().filter(productDto -> isactive.equals(productDto .getIsactive().toString())).collect(Collectors.toSet());
        }
        List<ProductDto> resultPage = new ArrayList<>(resultSet);
        /*分页处理*/
        if (pagenum != null && pagesize != null) {

            PageInfo<ProductDto> pageInfo = PageUtil.startPage(resultPage, Integer.parseInt(pagenum), Integer.parseInt(pagesize));
            return CommonResult.success(pageInfo);
        }
        return CommonResult.success(resultPage);
    }

    @PutMapping("/changeStatus")
    public CommonResult changeStatus(Integer id, Boolean saleable) {
        Boolean result = productService.changeStatus(id, saleable);
        if (result) {
            return CommonResult.success(true);
        } else {
            return CommonResult.failed();
        }
    }

    @PostMapping("/deleteById")
    public CommonResult<Boolean> deleteById(Integer id) {
        boolean result = productService.deleteById(id);
        productRepository.deleteById(id);
        return CommonResult.success(result);
    }

    @PostMapping("/add")
    public CommonResult<Boolean> addProduct(@RequestBody Product product) {
        product.setSalescount(0);
        product.setIsactive(false);
        boolean save = productService.add(product);
        return CommonResult.success(save);
    }
    @PutMapping("/add")
    public CommonResult<Boolean> editProduct(@RequestBody Product product) {
        Product save = productService.update(product);
        return CommonResult.success(BeanUtil.isNotEmpty(save));
    }
}
